package test.algorithm.FastSlowPointer;


/**
 * 魔术师发牌问题
 * @author serenity
 *
 */
public class Magician {
	
	public static void main(String[] args){
		//创建并初始化有13个节点的链表， 0代表节点值为空
		Node header = null;
		Node pointer = header;
		for(int i=1;i<=13;i++){
			Node temp = new Magician.Node(0);
			if(header==null){
				header = temp;
			}else{
				pointer.next = temp;
			}
			pointer = temp;
			pointer.next = header;
		}
		System.out.print("创建13个节点的空链表:");
		printList(header);
		
		//根据魔术师发牌逆推牌的开始顺序
		pointer = header;
		int countNum = 1 ;
		while(true){
			//按顺序查找揭牌位置
			for(int i=1;i<countNum;i++){
				pointer = pointer.next;
				// 如果当前位置的牌已揭开，则该位置不计数
				if(pointer.num!=0){
					i--;
				}
			}
			
			// 设置揭牌位置的点数
			if(pointer.num==0){
				pointer.num = countNum;
				countNum++;
				//设置了当前位置，指针指向下一个位置
				pointer = pointer.next;
			}
			
			// 如果超出了13，跳出循环
			if(countNum>13){
				break;
			}
		}
		System.out.print("牌的开始顺序:");
		printList(header);
	}
	
	static class Node {
		private int num;
		private Node next;
		
		public Node(int num){
			this.num = num;
		}
	}
	
	/**
	 * 打印链表
	 * @param node
	 */
	static void printList(Node header){
		Node pointer = header;
		do{
			System.out.print(pointer.num+" ");
			pointer = pointer.next;
		}while(pointer!=null && pointer!=header);
		System.out.println();
	}

}
